<template>
  <div class="record">
    <div class="record--left">
      <div class="table--box">
        <a-table
          class="record-table"
          :pagination="false"
          :columns="columns"
          :data-source="tableData"
          :row-key="(record) => record.id"
          :loading="loading"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
          :customRow="customRow"
          :rowClassName="
            () => {
              return 'blue';
            }
          "
          :locale="{ emptyText: '暂无数据' }"
          :scroll="{ y: 585 }"
          @change="handelFilterState"
        >
          <!--          <div-->
          <!--              v-if="userInfo.level == 6"-->
          <!--              slot="filterDropdown"-->
          <!--              slot-scope="{-->
          <!--              setSelectedKeys,-->
          <!--              selectedKeys,-->
          <!--              confirm,-->
          <!--              clearFilters,-->
          <!--              column,-->
          <!--            }"-->
          <!--              style="padding: 8px"-->
          <!--          >-->
          <!--            <a-input-->
          <!--                v-ant-ref="(c) => (searchInput = c)"-->
          <!--                :placeholder="`输入查询的${column.title}`"-->
          <!--                :value="filterDropdActiveVal"-->
          <!--                style="width: 188px; margin-bottom: 8px; display: block"-->
          <!--                @change="-->
          <!--                (e) => {-->
          <!--                  !e.target.value &&-->
          <!--                    handleReset(clearFilters, column.dataIndex);-->
          <!--                  setSelectedKeys(e.target.value ? [e.target.value] : []);-->
          <!--                  filterDropdActiveVal = e.target.value;-->
          <!--                }-->
          <!--              "-->
          <!--                @pressEnter="-->
          <!--                () => handleSearch(selectedKeys, confirm, column.dataIndex)-->
          <!--              "-->
          <!--                allow-clear-->
          <!--            />-->
          <!--            <a-button-->
          <!--                type="primary"-->
          <!--                icon="search"-->
          <!--                size="small"-->
          <!--                style="width: 90px; margin-right: 8px"-->
          <!--                @click="-->
          <!--                () => handleSearch(selectedKeys, confirm, column.dataIndex)-->
          <!--              "-->
          <!--            >-->
          <!--              查询-->
          <!--            </a-button>-->
          <!--          </div>-->

          <div
            slot="filterDropdownPos"
            slot-scope="{ confirm, column }"
            style="padding: 8px"
          >
            <a-radio-group
              :value="filterPos"
              @change="(e) => onPosChange(e, confirm, column.dataIndex)"
              style="display: flex; flex-direction: column"
            >
              <a-radio style="height: 30px; line-height: 30px" value="颈动脉">
                颈动脉
              </a-radio>
              <a-radio style="height: 30px; line-height: 30px" value="甲状腺">
                甲状腺
              </a-radio>
              <a-radio style="height: 30px; line-height: 30px" value="肝胆胰">
                肝胆胰
              </a-radio>
              <a-radio style="height: 30px; line-height: 30px" value="脾脏">
                脾脏
              </a-radio>
              <a-radio style="height: 30px; line-height: 30px" value="泌尿">
                泌尿
              </a-radio>
              <a-radio style="height: 30px; line-height: 30px" :value="null">
                不限
              </a-radio>
            </a-radio-group>
          </div>
          <div
            slot="filterDropdownSex"
            slot-scope="{ confirm, column }"
            style="padding: 8px"
          >
            <a-radio-group
              :value="filterSex"
              @change="(e) => onSexChange(e, confirm, column.dataIndex)"
              style="display: flex; flex-direction: column"
            >
              <a-radio style="height: 30px; line-height: 30px" :value="1">
                男
              </a-radio>
              <a-radio style="height: 30px; line-height: 30px" :value="0">
                女
              </a-radio>
              <a-radio style="height: 30px; line-height: 30px" :value="null">
                不限
              </a-radio>
            </a-radio-group>
          </div>
          <div
            slot="filterDropdownModel"
            slot-scope="{ confirm, column }"
            style="padding: 8px"
          >
            <a-radio-group
              :value="filterModel"
              @change="(e) => onModelChange(e, confirm, column.dataIndex)"
              style="display: flex; flex-direction: column"
            >
              <a-radio style="height: 30px; line-height: 30px" value="远程模式">
                远程模式
              </a-radio>
              <a-radio style="height: 30px; line-height: 30px" value="自主模式">
                自主模式
              </a-radio>
              <a-radio style="height: 30px; line-height: 30px" value="">
                不限
              </a-radio>
            </a-radio-group>
          </div>
          <div slot="filterDropdownEvaluate">
            <div class="own--table--evaluate">
              <div class="own--table--evaluate--w">
                灰色代表未评价,绿色代表已评价!
              </div>
              <div class="own--table--evaluate--w">状态依次为:</div>
              <div
                class="own--table--evaluate--w"
                v-for="item in assessTips"
                :key="item"
              >
                {{ item }}
              </div>
            </div>
          </div>
          <a-icon
            slot="filterIcon"
            slot-scope="filtered"
            type="search"
            :style="{ color: filtered ? 'aqua' : undefined }"
          />
          <a-icon type="question-circle" slot="question-circle" />
          <span
            slot="pat_hospital"
            slot-scope="pat_hospital"
            class="record--span"
          >
            {{ pat_hospital ? pat_hospital : "无" }}
          </span>
          <span slot="images" slot-scope="images" class="record--span">
            {{ images ? images : "无" }}
          </span>
          <span slot="movies" slot-scope="movies" class="record--span">
            {{ movies ? movies : "无" }}
          </span>
          <span slot="state" slot-scope="state">
            <span
              :class="[
                'state--tag',
                {
                  noCheck: state === 0,
                  checkAndEnd:
                    state === 1 || state === 3 || state === 5 || state == 7,
                  hasRep: state === 4,
                },
              ]"
            >
              {{ stateInfo[state] }}
            </span>
          </span>
          <span slot="sex" slot-scope="sex" class="record--span">
            {{ sex ? "男" : "女" }}
          </span>
          <span slot="model" slot-scope="model">
            {{
              model == "自主模式" || model == "自动模式"
                ? "自动模式"
                : "远程模式"
            }}
          </span>
          <span slot="evaluate" slot-scope="evaluate">
            <span v-for="(item, index) in evaluate" :key="item.name + index">
              <a-avatar
                :style="{ backgroundColor: item.color }"
                size="small"
              ></a-avatar>
            </span>
          </span>
          <span slot="action" slot-scope="record">
            <span
              class="table--action--text"
              @click.self="exportFiles2(record)"
              v-show="userInfo.level == 1 || userInfo.level == 8"
              >导出</span
            >
          </span>
        </a-table>
      </div>
      <div class="pagination--box">
        <button
          class="table--reset--btn"
          title="重置所有筛选条件"
          @click="handlefilterReset"
        >
          重置
        </button>
        <a-config-provider :locale="locale">
          <a-pagination
            v-model="current"
            show-quick-jumper
            :page-size-options="pageSizeOptions"
            :total="total"
            show-size-changer
            :page-size="pageSize"
            @showSizeChange="onShowSizeChange"
            @change="handleTableChange"
          >
            <template slot="buildOptionText" slot-scope="props">
              <span v-if="props.value !== '60'">{{ props.value }}条/页</span>
            </template>
          </a-pagination>
        </a-config-provider>
      </div>
    </div>
    <div
      :class="['record--right', { noImg: !rightImgs || rightImgs.length == 0 }]"
      @mouseleave="handleMouseleave"
    >
      <div class="hospital--title2">
        <span>检查影像</span>
      </div>
      <div class="noimg--box" v-show="!rightImgs || rightImgs.length == 0">
        <svg
          t="1640244737865"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="1313"
          width="64"
          height="64"
        >
          <path
            d="M512 0C228.430769 0 0 228.430769 0 512s228.430769 512 512 512 512-228.430769 512-512S795.569231 0 512 0z m0 59.076923c102.4 0 196.923077 35.446154 275.692308 94.523077L153.6 787.692308c-59.076923-74.830769-94.523077-173.292308-94.523077-275.692308C59.076923 263.876923 263.876923 59.076923 512 59.076923z m0 905.846154c-102.4 0-196.923077-35.446154-275.692308-94.523077L870.4 236.307692c59.076923 74.830769 94.523077 173.292308 94.523077 275.692308 0 248.123077-204.8 452.923077-452.923077 452.923077z"
            fill="#8a8a8a"
            p-id="1314"
          ></path>
        </svg>
        <span>暂无图片</span>
      </div>

      <div
        class="imgs--box"
        v-for="(item, index) in rightImgs"
        :key="index"
        @click="handlePreview(item)"
        @mouseenter="handleMouseenter(item)"
      >
        <img
          :src="item.url"
          alt=""
          class="imgs--box--img"
          v-if="!item.isVideo"
        />
        <video
          @dblclick="handleVideoDblClick(item.url, item.param_id)"
          :src="item.url"
          v-if="item.isVideo"
          controls
          controlsList="nodownload nofullscreen noplaybackrate"
          disablePictureInPicture
          @mouseenter="handleMouseleave"
        ></video>
        <svg
          v-if="userInfo.level == 1 || userInfo.level == 5"
          @click.stop="deleteImgAndVideo(item)"
          t="1646875744020"
          class="delete--icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="2119"
          width="20"
          height="20"
        >
          <path
            d="M612.693333 170.666667l8.533334 42.666666H402.773333l8.533334-42.666666h201.386666z m-293.632 25.941333a86.186667 86.186667 0 0 0-1.706666 16.725333H170.666667a42.666667 42.666667 0 0 0 0 85.333334h682.666666a42.666667 42.666667 0 1 0 0-85.333334h-146.730666c0-5.504-0.554667-11.093333-1.706667-16.725333l-8.533333-42.666667A85.333333 85.333333 0 0 0 612.778667 85.333333H411.306667a85.333333 85.333333 0 0 0-83.712 68.608l-8.533334 42.666667zM426.666667 469.333333a42.666667 42.666667 0 0 0-42.666667 42.666667v170.666667a42.666667 42.666667 0 1 0 85.333333 0v-170.666667a42.666667 42.666667 0 0 0-42.666666-42.666667z m128 42.666667a42.666667 42.666667 0 1 1 85.333333 0v170.666667a42.666667 42.666667 0 1 1-85.333333 0v-170.666667zM255.402667 384A42.666667 42.666667 0 0 1 298.666667 426.069333L301.738667 640H301.653333a42.666667 42.666667 0 1 1-85.290666-2.176l-2.986667-210.56A42.666667 42.666667 0 0 1 255.36 384z m51.925333 396.586667h0.042667A103.381333 103.381333 0 0 0 406.698667 853.333333h210.602666c54.186667 0 98.56-40.789333 103.210667-92.757333L725.333333 426.069333a42.666667 42.666667 0 0 1 85.333334 1.194667l-4.864 337.365333-0.128 1.365334C798.08 863.872 715.562667 938.666667 617.301333 938.666667H406.698667a188.885333 188.885333 0 0 1-180.096-130.389334 42.666667 42.666667 0 0 1 80.725333-27.648z"
            p-id="2120"
            fill="#e6e6e6"
          ></path>
        </svg>
        <span class="tag--index" v-if="item.index">{{ index + 1 }}</span>
      </div>
    </div>
    <div class="record--btn--box">
      <a-spin :spinning="isbulkDelete">
        <a-space size="large">
          <a-popconfirm
            ok-text="确定"
            cancel-text="取消"
            @confirm="blindEditing"
            placement="bottom"
            v-if="userInfo.level == 1"
            :disabled="selectedRowKeys.length == 0 || !selectRecord"
          >
            <div slot="title">
              <div>{{ blindTips }}</div>
              <div>注:已编盲的记录不参与二次编盲</div>
              <div>注:一经编盲不可修改</div>
            </div>
            <button
              v-preventReClick
              :class="[
                'btn',
                { dis: selectedRowKeys.length == 0 || !selectRecord },
              ]"
            >
              编盲
            </button>
          </a-popconfirm>
          <button
            v-preventReClick
            v-if="userInfo.level == 1 || userInfo.level == 8"
            @click="relation"
            class="btn"
          >
            关联
          </button>
          <button
            title="将数据导出到xlsx文件"
            v-preventReClick
            @click="batchExportToExcel"
            :class="[
              'btn',
              {
                dis: tableData.length === 0 || !selectRecord,
              },
            ]"
            v-if="userInfo.level == 1 || userInfo.level == 8"
            :disabled="tableData.length === 0 || !selectRecord"
          >
            批量导出
          </button>
          <button
            title="导出编盲记录"
            v-preventReClick
            @click="batchExportBlind"
            :class="['btn']"
            v-if="userInfo.level == 1"
          >
            导出编盲记录
          </button>
        </a-space>
      </a-spin>
    </div>
    <div class="preview--image--wrap" v-show="previewVisible">
      <div class="preview--image--box">
        <img :src="previewImage" alt="" class="preview--image--img" />
        <i class="preview--image--sub"
          >{{ previewImgIndex + 1 }}/{{ previewImgS.length }}</i
        >
      </div>
    </div>
    <div class="report--video" v-show="watchVideoKey">
      <div class="report--video--wrap">
        <VideoComp
          :status="watchVideoKey"
          :videoSrc="curVideo"
          :videoId="curVideoId"
          :curDocRecord="selectRecord"
          @on-chosevideo="chosevideo"
          @on-videoByDir="videoByDir"
          ref="videocomp"
          :videoS="videoS"
        />
      </div>
    </div>
    <ModalSlot
      :visible="relationKey"
      title="设置关联医生"
      @handleCancel="relationKey = false"
      @handleOk="relationKey = false"
      :width="600"
    >
      <div class="modal--box--wrap">
        <div class="relation--box">
          <div class="relation--box--item">
            <div class="relation--box--title">受试者筛选号:</div>
            <a-checkbox
              :indeterminate="indeterminate"
              :checked="relationCheckAll"
              @change="handleRelationCheckAll"
              >全选</a-checkbox
            >
            <a-checkbox-group
              v-model="relationSno"
              @change="handleRelation"
            ></a-checkbox-group>
            <a-checkbox-group v-model="relationSno">
              <a-checkbox
                :style="{
                  display: 'block',
                  height: '30px',
                  lineHeight: '30px',
                  margin: 0,
                }"
                :value="item.value"
                v-for="item in relationSnoList"
                :key="item.value"
              >
                {{ item.label }}
              </a-checkbox>
            </a-checkbox-group>
          </div>

          <div class="relation--box--item">
            <div class="relation--box--title">关联医生:</div>
            <a-radio-group v-model="relationDoctor">
              <a-radio
                :style="{
                  display: 'block',
                  height: '30px',
                  lineHeight: '30px',
                }"
                :value="item.value"
                v-for="item in userList"
                :key="item.value"
              >
                {{ item.label }}
              </a-radio>
            </a-radio-group>
          </div>
        </div>
        <div class="modal--box--footer--con2">
          <a-space size="large">
            <button @click="relationKey = false" class="modal-btn cancal">
              取消
            </button>
            <a-popconfirm
              title="关联后不可修改,确定关联?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="relationSubmit"
              placement="bottom"
            >
              <button class="modal-btn">确定</button>
            </a-popconfirm>
          </a-space>
        </div>
      </div>
    </ModalSlot>
    <div class="export--modal" v-show="export_modal">
      <div class="export_modal_box">
        <div>
          <a-spin tip="正在导出请稍等..."> </a-spin>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  updateRecord,
  getRecordsByFilterNoPaging,
  // findRecordAndPatient,
} from "@/api/recordInfo";
import ModalSlot from "@/components/ModalSlot";
import moment from "moment";
import { mapState } from "vuex";
import zhCN from "ant-design-vue/lib/locale-provider/zh_CN";
import VideoComp from "@/components/PaVideoComp";
import {
  deleteArrById3,
  stateInfo,
  statusOptions,
  modeOptions,
  genderOpts,
  unique2,
} from "@/utils";
import {
  exportXlsxFile,
  // exportToExcel,
  // dellDataByRecord,
  timeDifference,
  dellDataByForms,
  exportToWord,
  exportToWord2
} from "@/utils/exportFile";
import { getUserList } from "@/api/login";
import {
  getEvaluationExamRecords,
  relationRecord,
  getNoRelationSno,
  blindEditing,
  getEvaluationExamRecordsFilter,
} from "@/api/assess";
import { addLogInfo } from "@/api/logInfo";
import JSZip from "jszip";
import { saveAs } from "file-saver";
export default {
  name: "RecordComp",
  props: ["linkStatus", "status"],
  data() {
    return {
      loading: false,
      columns: [
        {
          title: "筛选号",
          dataIndex: "sNo",
          key: "sNo",
          ellipsis: true,
          width: 100,
        },
        {
          title: "编盲号",
          dataIndex: "magic6",
          key: "magic6",
          scopedSlots: { customRender: "magic6" },
          ellipsis: true,
          width: 70,
        },
        {
          title: "编盲组号",
          dataIndex: "magic4",
          key: "magic4",
          scopedSlots: { customRender: "magic4" },
          ellipsis: true,
          width: 90,
        },
        {
          title: "关联医生",
          dataIndex: "magic5",
          key: "magic5",
          scopedSlots: { customRender: "magic5" },
          ellipsis: true,
          width: 85,
        },
        {
          title: "检查部位",
          dataIndex: "pos_show",
          key: "pos_show",
          ellipsis: true,
          width: 90,
          scopedSlots: {
            filterDropdown: "filterDropdownPos",
            filterIcon: "filterIcon",
            customRender: "customRender",
          },
        },
        {
          title: "开始时间",
          dataIndex: "startAt",
          key: "startAt",
          ellipsis: true,
          width: 150,
          sorter: (a, b) => {
            return a.startAt > b.startAt ? 1 : -1;
          },
        },
        {
          title: "结束时间",
          dataIndex: "endAt",
          key: "endAt",
          ellipsis: true,
          width: 150,
        },
        {
          title: "耗时",
          dataIndex: "totalTime",
          key: "totalTime",
          ellipsis: true,
          width: 60,
        },
        {
          title: "检查状态",
          key: "state",
          dataIndex: "state",
          ellipsis: true,
          width: 90,
          scopedSlots: {
            filterDropdown: "filterDropdownState",
            filterIcon: "filterIcon",
            customRender: "state",
          },
        },
        {
          title: "评价状态",
          dataIndex: "evaluate",
          key: "evaluate",
          ellipsis: true,
          width: 270,
          scopedSlots: {
            filterDropdown: "filterDropdownEvaluate",
            filterIcon: "question-circle",
            customRender: "evaluate",
          },
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" },
          ellipsis: true,
          width: 100,
        },
      ],
      tableData: [], //检查记录数据
      stateInfo: stateInfo,
      pageSizeOptions: ["10", "20", "30", "40", "50", "100", "500"],
      total: 0,
      current: 1,
      pageSize: 10,
      selectedRowKeys: [], //选择的检查记录数据集合
      selectRecord: "", //当前选择的检查记录
      detailRecord: "", //点击详情的记录
      previewVisible: false,
      previewImage: "",
      previewImgIndex: 0, //预览的图片索引
      previewImgInfo: "", //预览的图片信息
      checkStatusVisible: false,
      searchInput: null,
      searchedColumn: "",
      searchText: "",
      searchParams: {},
      locale: zhCN,
      form1: this.$form.createForm(this, { name: "coordinated" }),
      sex: 1,
      year: "",
      options: genderOpts,
      modeOptions: modeOptions,
      statusOptions: statusOptions,
      checkTime: [],
      checkStatus: null,
      newCheckVisible: false,
      isMonths: false,
      watchVideoKey: false, //查看视频key
      videoS: "", //视频数组
      curVideo: "", //当前视频地址
      curVideoId: "",
      isbulkDelete: false,
      filterDropdActiveVal: "", //筛选条件val
      filterSex: "",
      filterState: "",
      filterModel: "",
      filterPos: "",
      relationKey: false,
      userList: [],
      relationDoctor: "",
      relationSnoList: [],
      relationSno: [],
      relationCheckAll: false,
      indeterminate: true,
      export_modal: false,
      export_pro: 0,
      forms: [],
    };
  },
  mounted() {
    this.dellColumns();
    if (this.userInfo.level == 1) {
      if (window.localStorage.getItem("createdAt")) {
        this.checkTime = JSON.parse(window.localStorage.getItem("createdAt"));
      }
    } else {
      this.checkTime = [];
    }

    if (window.localStorage.getItem("current")) {
      this.current = parseInt(window.localStorage.getItem("current"));
    }
    if (window.localStorage.getItem("pageSize")) {
      this.pageSize = parseInt(window.localStorage.getItem("pageSize"));
    }
    if (window.sessionStorage.getItem("filters")) {
      this.searchParams = JSON.parse(window.sessionStorage.getItem("filters"));
      for (const prop in this.searchParams) {
        console.log(`this.searchParams prop`, this.searchParams[prop]);
        if (this.searchParams[prop] || prop == `sex`) {
          this.handleTableFiltered(prop, true);
        }
      }
    }

    this.init();

    //监听更新选择的记录函数
    this.$EventBus.$on("updateSelectRecord", this.updateSelectRecord);
    //
    this.$EventBus.$on("updateCurPage", this.updateCurPage);
    //监听切换报告
    this.$EventBus.$on("changeReport", this.getChangeReport);
  },
  computed: {
    ...mapState([
      "userInfo",
      "SERVERBASE_URL",
      "RECORD_URL",
      "MANAGA_URL",
      "blindReview",
    ]),
    //右侧图片和视频
    rightImgs() {
      if (!this.selectRecord) return [];
      const parseJson = (data) => (data ? JSON.parse(data) : []);
      let imgS = unique2(parseJson(this.selectRecord.reportimg)).map(
        (item) => ({
          ...item,
          url: item.image || item.url,
        })
      );
      let videos = parseJson(this.selectRecord.videos);
      const addIndex = (items) =>
        items.map((item, index) => ({ ...item, index: index + 1 }));
      if (imgS.length && videos.length) {
        const combined = [...videos, ...imgS];
        return combined[0].index
          ? combined.sort((a, b) => a.index - b.index)
          : addIndex(combined);
      }
      if (videos.length) {
        return videos[0].index ? videos : addIndex(videos);
      }
      if (imgS.length) {
        return imgS[0].index ? imgS : addIndex(imgS);
      }
      return [];
    },
    //预览的图片
    previewImgS() {
      if (!this.selectRecord) {
        return [];
      } else {
        return this.selectRecord.reportimg
          ? JSON.parse(this.selectRecord.reportimg)
          : [];
      }
    },
    //该患者的所有检查记录中有已出报告吗
    recordDisabled() {
      if (
        (this.detailRecord && this.detailRecord.state === 4) ||
        this.detailRecord.state === 6
      )
        return true;
      return false;
    },
    canShowInfo() {
      if (this.blindReview) {
        return false;
      } else {
        return true;
      }
    },
    blindTips() {
      return `已选择${this.selectedRowKeys.length}条数据进行编盲!`;
    },
    assessTips() {
      let str_arr = ["对照医生非盲评", "对照医生盲评"];
      const info = {
        0: "扫查影像评价",
        1: "标准切面评价",
      };
      this.forms.forEach((item) => {
        if (item.level == 6) {
          str_arr.push(`专家:${item.doctorName}${info[item.evaluationID]}`);
        }
      });
      return str_arr;
    },
  },
  watch: {
    pageSize(val) {
      if (val) {
        this.current = 1;
        this.getRecord();
      }
    },
    previewVisible(val) {
      if (val) {
        document.addEventListener("keyup", this.listenerKeyUp);
      } else {
        document.removeEventListener("keyup", this.listenerKeyUp);
      }
    },
    status(val) {
      if (val) {
        this.getRecord();
      }
    },
    selectRecord(newVal, oldVal) {
      if (newVal && oldVal && newVal.id != oldVal.id) {
        this.previewImgIndex = 0;
        this.mockClick();
      }
    },
  },
  components: {
    ModalSlot,
    VideoComp,
  },
  methods: {
    dellColumns() {
      if (this.userInfo.level == 6) {
        if (this.blindReview) {
          console.log("盲评", this.columns);
          this.columns = [
            {
              title: "编盲号",
              dataIndex: "magic6",
              key: "magic6",
              scopedSlots: { customRender: "magic6" },
              ellipsis: true,
              width: 200,
            },
            {
              title: "检查部位",
              dataIndex: "pos_show",
              key: "pos_show",
              ellipsis: true,
              width: 200,
              scopedSlots: {
                filterDropdown: "filterDropdownPos",
                filterIcon: "filterIcon",
                customRender: "customRender",
              },
            },
            {
              title: "检查状态",
              key: "state",
              dataIndex: "state",
              scopedSlots: {
                filterDropdown: "filterDropdownState",
                filterIcon: "filterIcon",
                customRender: "state",
              },
            },
            {
              title: "评价状态",
              dataIndex: "evaluate",
              key: "evaluate",
              scopedSlots: { customRender: "evaluate" },
              ellipsis: true,
              width: 400,
            },
            {
              title: "操作",
              key: "action",
              scopedSlots: { customRender: "action" },
            },
          ];
        } else {
          this.columns = [
            {
              title: "受试者筛选号",
              dataIndex: "sNo",
              key: "sNo",
              ellipsis: true,
              width: 200,
              scopedSlots: {
                filterDropdown: "filterDropdown",
                filterIcon: "filterIcon",
                customRender: "customRender",
              },
              onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                  let filters = window.sessionStorage.getItem("filters");
                  setTimeout(() => {
                    this.searchInput.focus();
                    if (filters) {
                      filters = JSON.parse(filters);
                      this.filterDropdActiveVal = filters["sNo"];
                      console.log(
                        "filterDropdActiveVal",
                        this.filterDropdActiveVal
                      );
                    }
                  }, 0);
                }
              },
            },
            {
              title: "检查部位",
              dataIndex: "pos_show",
              key: "pos_show",
              ellipsis: true,
              width: 200,
              scopedSlots: {
                filterDropdown: "filterDropdownPos",
                filterIcon: "filterIcon",
                customRender: "customRender",
              },
            },
            {
              title: "检查状态",
              key: "state",
              dataIndex: "state",
              scopedSlots: {
                filterDropdown: "filterDropdownState",
                filterIcon: "filterIcon",
                customRender: "state",
              },
            },
            {
              title: "评价状态",
              dataIndex: "evaluate",
              key: "evaluate",
              scopedSlots: { customRender: "evaluate" },
              ellipsis: true,
              width: 400,
            },
            {
              title: "操作",
              key: "action",
              scopedSlots: { customRender: "action" },
            },
          ];
        }
      } else if (this.userInfo.level == 7) {
        if (this.blindReview) {
          console.log("盲评", this.columns);
          this.columns = [
            {
              title: "编盲号",
              dataIndex: "magic6",
              key: "magic6",
              scopedSlots: { customRender: "magic6" },
              ellipsis: true,
              width: 200,
            },
            {
              title: "检查部位",
              dataIndex: "pos_show",
              key: "pos_show",
              ellipsis: true,
              width: 200,
              scopedSlots: {
                filterDropdown: "filterDropdownPos",
                filterIcon: "filterIcon",
                customRender: "customRender",
              },
            },
            {
              title: "检查状态",
              key: "state",
              dataIndex: "state",
              scopedSlots: {
                filterDropdown: "filterDropdownState",
                filterIcon: "filterIcon",
                customRender: "state",
              },
            },
            {
              title: "评价状态",
              dataIndex: "evaluate",
              key: "evaluate",
              scopedSlots: { customRender: "evaluate" },
              ellipsis: true,
              width: 400,
            },
            {
              title: "操作",
              key: "action",
              scopedSlots: { customRender: "action" },
            },
          ];
        } else {
          this.columns = [
            {
              title: "受试者筛选号",
              dataIndex: "sNo",
              key: "sNo",
              ellipsis: true,
              width: 200,
              scopedSlots: {
                filterDropdown: "filterDropdown",
                filterIcon: "filterIcon",
                customRender: "customRender",
              },
              onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                  let filters = window.sessionStorage.getItem("filters");
                  setTimeout(() => {
                    this.searchInput.focus();
                    if (filters) {
                      filters = JSON.parse(filters);
                      this.filterDropdActiveVal = filters["sNo"];
                      console.log(
                        "filterDropdActiveVal",
                        this.filterDropdActiveVal
                      );
                    }
                  }, 0);
                }
              },
            },
            {
              title: "检查部位",
              dataIndex: "pos_show",
              key: "pos_show",
              ellipsis: true,
              width: 200,
              scopedSlots: {
                filterDropdown: "filterDropdownPos",
                filterIcon: "filterIcon",
                customRender: "customRender",
              },
            },
            {
              title: "检查状态",
              key: "state",
              dataIndex: "state",
              scopedSlots: {
                filterDropdown: "filterDropdownState",
                filterIcon: "filterIcon",
                customRender: "state",
              },
            },
            {
              title: "评价状态",
              dataIndex: "evaluate",
              key: "evaluate",
              scopedSlots: { customRender: "evaluate" },
              ellipsis: true,
              width: 400,
            },
            {
              title: "操作",
              key: "action",
              scopedSlots: { customRender: "action" },
            },
          ];
        }
      } else if (this.userInfo.level == 8) {
        this.columns = [
          {
            title: "筛选号",
            dataIndex: "sNo",
            key: "sNo",
            ellipsis: true,
            width: 100,
          },
          {
            title: "关联医生",
            dataIndex: "magic5",
            key: "magic5",
            scopedSlots: { customRender: "magic5" },
            ellipsis: true,
            width: 85,
          },
          {
            title: "检查部位",
            dataIndex: "pos_show",
            key: "pos_show",
            ellipsis: true,
            width: 90,
            scopedSlots: {
              filterDropdown: "filterDropdownPos",
              filterIcon: "filterIcon",
              customRender: "customRender",
            },
          },
          {
            title: "开始时间",
            dataIndex: "startAt",
            key: "startAt",
            ellipsis: true,
            width: 150,
            sorter: (a, b) => {
              return a.startAt > b.startAt ? 1 : -1;
            },
          },
          {
            title: "结束时间",
            dataIndex: "endAt",
            key: "endAt",
            ellipsis: true,
            width: 150,
          },
          {
            title: "耗时",
            dataIndex: "totalTime",
            key: "totalTime",
            ellipsis: true,
            width: 60,
          },
          {
            title: "检查状态",
            key: "state",
            dataIndex: "state",
            ellipsis: true,
            width: 90,
            scopedSlots: {
              filterDropdown: "filterDropdownState",
              filterIcon: "filterIcon",
              customRender: "state",
            },
          },
          {
            title: "评价状态",
            dataIndex: "evaluate",
            key: "evaluate",
            ellipsis: true,
            width: 270,
            scopedSlots: {
              filterDropdown: "filterDropdownEvaluate",
              filterIcon: "question-circle",
              customRender: "evaluate",
            },
          },
          {
            title: "操作",
            key: "action",
            scopedSlots: { customRender: "action" },
            ellipsis: true,
            width: 100,
          },
        ];
      }
    },
    init() {
      this.loading = true;
      this.getRecord();
    },
    //查询
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      this.searchText = selectedKeys[0];
      if (selectedKeys[0] == "%") {
        this.searchText = "/%/";
      }
      this.searchedColumn = dataIndex;
      this.searchParams[dataIndex] = selectedKeys[0];
      this.current = 1;
      //this.getRecord();
    },
    //查询重置
    handleReset(clearFilters, dataIndex) {
      if (this.searchParams[dataIndex]) {
        this.searchParams[dataIndex] = "";
      }
      this.searchText = "";
      this.searchedColumn = "";
      this.current = 1;
      if (window.sessionStorage.getItem("filters")) {
        const filters = JSON.parse(window.sessionStorage.getItem("filters"));
        if (filters[dataIndex]) {
          delete filters[dataIndex];
          window.sessionStorage.setItem("filters", JSON.stringify(filters));
        }
      }
      this.handleTableFiltered(dataIndex, false);
      clearFilters();
      this.getRecord();
    },
    handelFilterState(pagination, filters, sorter) {
      console.log("Various parameters", pagination, filters, sorter);
      for (var props in filters) {
        if (filters[props].length > 0) {
          console.log("props：", props, filters[props][0]);
          this.searchParams[props] = filters[props][0];
          if (props == "model" && filters[props][0] == "local") {
            this.searchParams[props] = "自主模式";
          } else if (props == "model" && filters[props][0] == "remote") {
            this.searchParams[props] = "远程模式";
          } else {
            this.searchParams[props] = filters[props][0];
          }
        } else {
          console.log("props：", props, filters[props]);
          delete this.searchParams[props];
        }
      }
      window.sessionStorage.setItem(
        "filters",
        JSON.stringify(this.searchParams)
      );
      this.current = 1;
      this.getRecord();
    },
    //检查日期切换
    onDateChange(date, dateString) {
      console.log("检查日期切换", date, dateString);
      this.checkTime = dateString;
      window.localStorage.setItem("createdAt", JSON.stringify(dateString));
      this.current = 1;
      window.localStorage.setItem("current", 1);
      this.getRecord();
    },
    //性别筛选
    onSexChange(e, confirm, dataIndex) {
      confirm();
      if (typeof e.target.value != "number") {
        delete this.searchParams[dataIndex];
        this.handleTableFiltered(dataIndex, false);
      } else {
        this.searchParams[dataIndex] = e.target.value;
        this.handleTableFiltered(dataIndex, true);
      }
      window.sessionStorage.setItem(
        "filters",
        JSON.stringify(this.searchParams)
      );
      this.current = 1;
      this.getRecord();
    },
    //检查模式筛选
    onModelChange(e, confirm, dataIndex) {
      confirm();
      if (!e.target.value) {
        delete this.searchParams[dataIndex];
        this.handleTableFiltered(dataIndex, false);
      } else {
        this.searchParams[dataIndex] = e.target.value;
        this.handleTableFiltered(dataIndex, true);
      }
      window.sessionStorage.setItem(
        "filters",
        JSON.stringify(this.searchParams)
      );
      this.current = 1;
      this.getRecord();
    },
    //检查状态筛选
    onStateChange(e, confirm, dataIndex) {
      confirm();
      if (typeof e.target.value != "number") {
        delete this.searchParams[dataIndex];
        this.handleTableFiltered(dataIndex, false);
      } else {
        this.searchParams[dataIndex] = e.target.value;
        this.handleTableFiltered(dataIndex, true);
      }
      window.sessionStorage.setItem(
        "filters",
        JSON.stringify(this.searchParams)
      );
      this.current = 1;
      this.getRecord();
    },
    onPosChange(e, confirm, dataIndex) {
      confirm();
      if (!e.target.value) {
        delete this.searchParams[dataIndex];
        this.handleTableFiltered(dataIndex, false);
      } else {
        this.searchParams[dataIndex] = e.target.value;
        this.handleTableFiltered(dataIndex, true);
      }
      window.sessionStorage.setItem(
        "filters",
        JSON.stringify(this.searchParams)
      );
      this.current = 1;
      this.getRecord();
    },
    //重置筛选条件
    handlefilterReset() {
      try {
        this.filterSex = "";
        this.filterState = "";
        this.filterModel = "";
        this.filterPos = "";
        this.columns.forEach((item) => {
          if (item.filtered && item.key != "createdAt") {
            item.filtered = false;
          }
        });
        this.searchParams = {};
        window.sessionStorage.setItem("filters", JSON.stringify({}));
        this.current = 1;
        this.getRecord();
      } catch (error) {
        console.log("handlefilterReset error:", error);
      }
    },
    //获取记录
    getRecord() {
      const vm = this;
      let params = {
        page: this.current,
        limit: this.pageSize,
        level: this.userInfo.level == 8 ? 1 : this.userInfo.level,
        name: this.userInfo.name,
        blind: this.blindReview ? 1 : 0,
      };
      for (let props in this.searchParams) {
        if (this.searchParams[props]) {
          params[props] = this.searchParams[props];
        }
        if (props == "sex") {
          params[props] = this.searchParams[props];
        }
        if (props == "state") {
          params[props] = this.searchParams[props];
        }
        if (props == "pos_show") {
          params["pos"] = this.searchParams[props];
          delete params["pos_show"];
        }
      }
      console.log("查询参数:", params, this.searchParams);
      getEvaluationExamRecordsFilter(this.RECORD_URL, params)
        .then((res) => {
          vm.loading = false;
          if (res.code == 200) {
            const evaluateType = {
              0: "合格",
              1: "识别",
              2: "一致",
            };
            vm.total = res.data.count;
            vm.tableData = res.data.rows.map((item) => {
              item.images = item.reportimg
                ? JSON.parse(item.reportimg).length
                : "";
              item.startAt = moment(item.startAt).format("YYYY-MM-DD HH:mm:ss");
              item.movies = item.videos ? JSON.parse(item.videos).length : "";
              item.pat_hospital = item.patient_user_info
                ? JSON.parse(item.patient_user_info).hospital
                  ? JSON.parse(item.patient_user_info).hospital.name
                  : ``
                : ``;
              item.isCanExport = item.forms
                ? item.forms.every((i) => i.evaluationResult)
                : true;
              item.totalTime = timeDifference(item.startAt, item.endAt) + "s";
              item.evaluate =
                item.forms.length > 0
                  ? item.forms.map((f) => {
                      return {
                        name: f.doctorName.includes("zhuan") ? "Z" : "Y",
                        color: f.evaluationResult == "" ? "#8d8989" : "#87d068",
                        type: evaluateType[f.evaluationID],
                      };
                    })
                  : [];
              if (item.magic2 && item.pos == "腹部") {
                item.pos_show = item.magic2 == "liver" ? "肝胆胰" : "脾脏";
              } else {
                item.pos_show = item.pos;
              }
              return item;
            });
            if (vm.selectRecord) {
              vm.selectRecord = res.data.rows.find((i) => {
                return i.id == vm.selectRecord.id;
              });
            }
            vm.forms = vm.tableData.length > 1 ? vm.tableData[0].forms : [];
            console.log(vm.tableData);
          }
        })
        .catch((err) => {
          console.log(err);
          vm.loading = false;
        });
    },
    //当前页码改变的回调
    handleTableChange(pagination) {
      console.log("current:", pagination);
      this.current = pagination;
      window.localStorage.setItem("current", pagination);
      this.getRecord();
      if (this.selectRecord) {
        this.selectedRowKeys = [];
        this.selectRecord = "";
      }
    },
    //每页条数改变的回调
    onShowSizeChange(current, pageSize) {
      console.log("onShowSizeChange", current, pageSize);
      this.pageSize = pageSize;
      window.localStorage.setItem("pageSize", pageSize);
    },
    //选择某条记录
    onSelectChange(selectedRowKeys, record) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      this.selectRecord = record.pop();
      if (this.selectRecord) {
        this.videoS = this.selectRecord.videos
          ? JSON.parse(this.selectRecord.videos)
          : [];
      }
      console.log("record: ", this.selectRecord);
    },
    //更新选择某条记录
    updateSelectRecord(params) {
      this.selectRecord = {
        ...this.selectRecord,
        ...params,
      };
    },
    //查看报告
    go2Report(val) {
      this.$router.push({
        name: "report3",
        params: { id: val.id, patient_sn: val.patient_sn },
      });
      window.localStorage.setItem(
        "tableData",
        JSON.stringify({
          tableData: this.tableData,
          currentPage: this.current,
          limit: this.pageSize,
          total: this.total,
        })
      );
      if (val.forms.length > 0) {
        window.localStorage.setItem("forms", JSON.stringify(val.forms));
      }
    },
    //预览图片
    handlePreview(data) {
      try {
        if (!data.isVideo) {
          this.previewVisible = false;
        }
      } catch (err) {
        console.log(err);
      }
    },
    //鼠标移入图片处理
    handleMouseenter(data) {
      try {
        if (!data.isVideo) {
          this.previewImgInfo = data;
          this.previewImage = data.image || data.url;
          this.previewVisible = true;
          this.rightImgs.forEach((item, index) => {
            if (item.param_id == data.param_id) {
              this.previewImgIndex = index;
            }
          });
        }
      } catch (err) {
        console.log(err);
      }
    },
    handleMouseleave() {
      try {
        if (this.previewVisible) {
          this.previewVisible = false;
          this.previewImgIndex = "leave";
        }
      } catch (err) {
        console.log(err);
      }
    },
    //根据方向处理预览图片
    handleGoPreview(dir) {
      if (!dir) return;
      if (dir == "left") {
        this.previewImgIndex--;
        if (this.previewImgIndex < 0) {
          this.previewImgIndex = 0;
        }
        if (this.previewImgIndex == 0) {
          this.$message.warning("第一张图片");
        }
      } else if (dir == "right") {
        this.previewImgIndex++;
        if (this.previewImgIndex > this.previewImgS.length - 1) {
          this.previewImgIndex = this.previewImgS.length - 1;
        }
        if (this.previewImgIndex == this.previewImgS.length - 1) {
          this.$message.warning("最后一张图片");
        }
      }
      this.previewImage =
        this.previewImgS[this.previewImgIndex].image ||
        this.previewImgS[this.previewImgIndex].url;
      this.previewImgInfo = this.previewImgS[this.previewImgIndex];
    },
    //监听键盘左右键
    listenerKeyUp(event) {
      const vm = this;
      try {
        if (event.keyCode == 37 || event.keyCode == 38) {
          this.handleGoPreview("left");
        } else if (event.keyCode == 39 || event.keyCode == 40) {
          this.handleGoPreview("right");
        } else if (event.keyCode == 46) {
          if (this.selectRecord.state === 4) {
            this.$message.warning("已出报告,不能删除图片!");
            return;
          }
          if (this.previewImgInfo) {
            //删除的是图片
            this.$confirm({
              title: "提示:",
              okText: "是",
              cancelText: "否",
              content: () => <div style="color:red;">是否删除该图片?</div>,
              async onOk() {
                const imgs = JSON.parse(vm.selectRecord.reportimg);
                const newImgs = deleteArrById3(
                  imgs,
                  vm.previewImgInfo.param_id
                );
                const params = {
                  id: vm.selectRecord.id,
                  patient_sn: vm.selectRecord.patient_sn,
                };
                const res = await updateRecord(
                  vm.RECORD_URL,
                  {
                    reportimg: JSON.stringify(newImgs),
                  },
                  params
                );
                if (res.code === 200) {
                  window.localStorage.setItem(
                    "deleteImg",
                    JSON.stringify(vm.previewImgInfo)
                  );
                  vm.previewImgInfo = "";
                  vm.previewImage = "";
                  vm.previewVisible = false;
                  vm.$message.success("删除成功！");
                  vm.getRecord();
                } else {
                  vm.$message.error("删除失败！");
                }
              },
              onCancel() {
                console.log("Cancel");
              },
              class: "test",
            });
          }
        }
      } catch (err) {
        console.log(err);
      }
    },
    //模拟点击元素
    mockClick() {
      $(".record--right").animate(
        {
          scrollTop: 0,
        },
        100
      );
    },
    //模糊查询
    customRow(record) {
      return {
        on: {
          click: () => {
            if (this.selectRecord) {
              if (this.selectRecord.id != record.id) {
                let keys = [];
                keys.push(record.id);
                this.selectedRowKeys = keys;
                this.selectRecord = record;
                this.videoS = this.selectRecord.videos
                  ? JSON.parse(this.selectRecord.videos)
                  : [];
                console.log(
                  "selectRecord",
                  this.selectRecord,
                  this.selectRecord.name,
                  this.videoS
                );
              } else {
                this.selectedRowKeys = [];
                this.selectRecord = "";
                this.videoS = "";
              }
            } else {
              let keys = [];
              keys.push(record.id);
              this.selectedRowKeys = keys;
              this.selectRecord = record;
              this.videoS = this.selectRecord.videos
                ? JSON.parse(this.selectRecord.videos)
                : [];
              console.log(
                "selectRecord",
                this.selectRecord,
                this.selectRecord.name,
                this.videoS
              );
            }
          },
          dblclick: () => {
            if (record.state != 0 && record.state != 1) {
              this.go2Report(record);
            } else {
              this.$message.warning("还没有检查报告!");
            }
          },
        },
      };
    },
    //更新当前页码
    updateCurPage(page) {
      this.current = page;
      console.log("当前页码", page);
    },
    //删除图片
    deleteImgAndVideo(data) {
      console.log(data);
      const vm = this;
      if (data.isVideo) {
        //删除的是电影
        console.log(vm.selectRecord.videos);
        this.$confirm({
          title: "提示:",
          okText: "是",
          cancelText: "否",
          content: () => <div style="color:red;">是否删除该电影?</div>,
          async onOk() {
            try {
              const videos = JSON.parse(vm.selectRecord.videos);
              const newVideos = deleteArrById3(videos, data.param_id);
              const params = {
                id: vm.selectRecord.id,
                patient_sn: vm.selectRecord.patient_sn,
              };
              const res = await updateRecord(
                vm.RECORD_URL,
                {
                  videos: JSON.stringify(newVideos),
                },
                params
              );
              if (res.code === 200) {
                vm.$message.success("删除成功！");
                vm.getRecord();
                window.localStorage.setItem("deleteImg", JSON.stringify(data));
              } else {
                vm.$message.console.error();
                ("删除失败！");
              }
            } catch (err) {
              console.log(err);
            }
          },
          onCancel() {
            console.log("Cancel");
          },
          class: "test",
        });
      } else {
        //删除的是图片
        this.$confirm({
          title: "提示:",
          okText: "是",
          cancelText: "否",
          content: () => <div style="color:red;">是否删除该图片?</div>,
          async onOk() {
            try {
              const imgs = JSON.parse(vm.selectRecord.reportimg);
              const newImgs = deleteArrById3(imgs, data.param_id);
              const params = {
                id: vm.selectRecord.id,
                patient_sn: vm.selectRecord.patient_sn,
              };
              const res = await updateRecord(
                vm.RECORD_URL,
                {
                  reportimg: JSON.stringify(newImgs),
                },
                params
              );
              if (res.code === 200) {
                vm.$message.success("删除成功！");
                vm.getRecord();
                window.localStorage.setItem("deleteImg", JSON.stringify(data));
              } else {
                vm.$message.console.error("删除失败！");
              }
            } catch (err) {
              console.log(err);
            }
          },
          onCancel() {
            console.log("Cancel");
          },
          class: "test",
        });
      }
    },
    //性别改变
    sexChange(e) {
      this.sex = e.target.value;
    },
    //日期改变处理函数
    dateChange(date, dateString) {
      this.birth = dateString;
      if (date) {
        let newYear = moment().diff(moment(dateString), "years");
        this.form1.setFieldsValue({ year: newYear });
      }
    },
    //不能选的日期
    disabledDate(current) {
      return current && current > Date.now();
    },
    //年纪改变处理函数
    yearChange(val) {
      if (val === "" || val === null || !$.isNumeric(val)) {
        this.$message.warning(`请输入正确的年龄!`);
        this.$nextTick(() => {
          this.form1.setFieldsValue({ year: 0 });
        });
        return;
      }
      this.isMonths = false;
      const now_year =
        val === 0
          ? new Date().getFullYear() - val
          : new Date().getFullYear() - val;
      let now_month = new Date().getMonth() + 1;
      let now_day = new Date().getDate();
      if (now_month < 10) {
        now_month = `0${now_month}`;
      }
      if (now_day < 10) {
        now_day = `0${now_day}`;
      }
      const nowT = `${now_year}${now_month}${now_day}`;
      this.birth = `${now_year}-${now_month}-${now_day}`;
      this.form1.setFieldsValue({ birth: moment(nowT) });
    },
    posHandleChange(value) {
      const vm = this;
      this.$nextTick(() => {
        vm.form1.setFieldsValue({ pos: value });
      });
    },
    posHandleSearch(value) {
      const vm = this;
      this.$nextTick(() => {
        vm.form1.setFieldsValue({ pos: value });
      });
    },
    posHandleBlur(value) {
      const vm = this;
      if (value) {
        value = value.substring(0, 20);
      }
      this.$nextTick(() => {
        vm.form1.setFieldsValue({ pos: value });
      });
    },
    //处理双击视频时间
    handleVideoDblClick(url, id) {
      try {
        console.log("查看视频", this.videoS);
        if (this.videoS.length > 0) {
          this.curVideo = url;
          this.curVideoId = id;
          this.watchVideoKey = true;
        } else {
          this.$message.warning("没有视频！");
        }
      } catch (error) {
        console.log("handleVideoDblClick", error);
      }
    },
    //切换视频
    videoByDir(dir) {
      try {
        const curVideoIndex = this.videoS.findIndex((item) => {
          return item.url == this.curVideo;
        });
        if (curVideoIndex == -1) {
          return;
        }
        if (dir == "right") {
          if (curVideoIndex == this.videoS.length - 1) {
            this.$message.warning("最后一个视频!");
            return;
          }
          this.curVideo = this.videoS[curVideoIndex + 1].url;
          this.curVideoId = this.videoS[curVideoIndex + 1].param_id;
        } else if (dir == "left") {
          if (curVideoIndex == 0) {
            this.$message.warning("第一个视频!");
            return;
          }
          this.curVideo = this.videoS[curVideoIndex - 1].url;
          this.curVideoId = this.videoS[curVideoIndex - 1].param_id;
        }
        this.$nextTick(() => {
          this.$refs.videocomp.initVideo();
        });
      } catch (err) {
        console.log(err);
      }
    },
    //关闭视频
    chosevideo() {
      try {
        console.log("关闭视频");
        this.watchVideoKey = false;
      } catch (err) {
        console.log(err);
      }
    },
    moment,
    //处理table筛选图标高亮
    handleTableFiltered(key, value) {
      try {
        this.columns.forEach((item) => {
          if (item.key == key) {
            item.filtered = value;
          }
        });
      } catch (err) {
        console.log(`handleTableFiltered`, err);
      }
    },
    //导出xlsx文件
    async exportFiles() {
      const levelInfo = {
        1: 1,
        2: 1,
        0: 0,
        5: 1,
        undefined: 0,
      };
      try {
        const params = {
          admin: levelInfo[this.userInfo.level],
        };
        let allow_sn = this.userInfo.allow_sn;
        for (let props in this.searchParams) {
          if (this.searchParams[props]) {
            params[props] = this.searchParams[props];
          }
          if (props == "sex") {
            params[props] = this.searchParams[props];
          }
          if (props == "state") {
            params[props] = this.searchParams[props];
          }
        }
        if (allow_sn.patient_sn) {
          params.patient_sn = Array.isArray(allow_sn.patient_sn)
            ? allow_sn.patient_sn
            : allow_sn.patient_sn
            ? [allow_sn.patient_sn]
            : [];
        }
        if (allow_sn.doctor_sn) {
          params.doctor_sn = Array.isArray(allow_sn.doctor_sn)
            ? allow_sn.doctor_sn
            : allow_sn.doctor_sn
            ? [allow_sn.doctor_sn]
            : [];
        }
        if (this.checkTime) {
          const hasTime = this.checkTime.every((item) => item);
          if (hasTime) {
            params.createdAt = this.checkTime;
          }
        } else {
          const hasTime = window.localStorage.getItem("createdAt");
          if (hasTime) {
            params.createdAt = JSON.parse(
              window.localStorage.getItem("createdAt")
            );
          }
        }
        const records_res = await getRecordsByFilterNoPaging(
          this.RECORD_URL,
          params
        );
        console.log("getRecordsByFilterNoPaging", records_res);
        if (records_res.code == 200) {
          const records = records_res.data.rows;
          if (records.length > 0) {
            const new_records = records.map((item) => {
              return {
                sNo: item.sNo,
                name: item.name,
                sex: item.sex ? "男" : "女",
                pat_hospital: item.patient_user_info
                  ? JSON.parse(item.patient_user_info).hospital
                    ? JSON.parse(item.patient_user_info).hospital.name
                    : ``
                  : ``,
                doc_hospital: item.doctor_user_info
                  ? JSON.parse(item.doctor_user_info).hospital
                    ? JSON.parse(item.doctor_user_info).hospital.name
                    : ``
                  : ``,
                year: item.year,
                pos: item.pos,
                startAt: moment(item.createdAt).format("YYYY-MM-DD HH:mm:ss"),
                model: item.model,
                state: stateInfo[item.state],
                patient_sn: item.patient_sn,
                tips: item.tips,
                images: item.reportimg ? JSON.parse(item.reportimg).length : 0,
                movies: item.videos ? JSON.parse(item.videos).length : 0,
              };
            });
            console.log("new_records", new_records);
            const headerMapping = {
              sNo: "患者ID",
              name: "姓名",
              sex: "性别",
              pat_hospital: "患者端医院",
              doc_hospital: "医生端医院",
              year: "年龄",
              pos: "检查部位",
              images: "图片数量",
              movies: "视频数量",
              startAt: "开始检查时间",
              model: "检查模式",
              state: "检查状态",
              patient_sn: "患者端SN",
              tips: "超声诊断结果",
            };
            exportXlsxFile(new_records, headerMapping, "数据", "");
          } else {
            this.$message.warning("导出数据为空!");
          }
        } else {
          this.$message.warning("导出失败!");
        }
      } catch (error) {
        console.log("exportFiles", error);
      }
    },
    handleRelation(checkedList) {
      this.indeterminate =
        !!checkedList.length &&
        checkedList.length < this.relationSnoList.length;
      this.relationCheckAll =
        checkedList.length === this.relationSnoList.length;
    },
    handleRelationCheckAll(e) {
      this.relationSno = e.target.checked
        ? this.relationSnoList.map((item) => item.value)
        : [];
      this.indeterminate = false;
      this.relationCheckAll = e.target.checked;
    },
    //关联
    async relation() {
      try {
        const relation_res = await getNoRelationSno(this.RECORD_URL);
        console.log("关联", relation_res);
        let params = {
          current: 1,
          pageSize: 20,
          level: this.userInfo.level == 8 ? 1 : this.userInfo.level,
          searchLevel: 7,
        };
        const res = await getUserList(this.SERVERBASE_URL, params);
        if (res.code == 200 && relation_res.code) {
          this.userList = res.data.rows.map((item) => {
            return {
              label: item.name,
              value: item.name,
              radioStyle: {
                display: "block",
                height: "30px",
                lineHeight: "30px",
              },
            };
          });
          this.relationSnoList = relation_res.data.list.map((item) => {
            return {
              label: item,
              value: item,
              radioStyle: {
                display: "block",
                height: "30px",
                lineHeight: "30px",
              },
            };
          });
        }
        this.relationKey = true;
      } catch (error) {
        console.log("relation error", error);
      }
    },
    //关联确认
    async relationSubmit() {
      try {
        if (this.relationSno.length == 0) {
          this.$message.warning("请选择受试者筛选号！");
          return;
        }
        if (!this.relationDoctor) {
          this.$message.warning("请选择关联医生！");
          return;
        }
        const params = [];
        this.relationSno.forEach((item) => {
          params.push({ key: item, value: this.relationDoctor });
        });
        const res = await relationRecord(this.RECORD_URL, { list: params });
        if (res.code == 200) {
          this.relationKey = false;
          this.$message.success("关联成功!");
          this.getRecord();
          addLogInfo(this.SERVERBASE_URL, {
            name: this.userInfo.name,
            type: "操作",
            event: "关联",
          });
        } else {
          this.$message.error("关联失败!");
        }
      } catch (error) {
        console.log("relationSubmit error", error);
      }
    },
    //编盲
    async blindEditing() {
      try {
        if (this.selectedRowKeys.length == 0) {
          this.$message.warning("请选择需要编盲的数据！");
          return;
        }
        const params = [];
        this.tableData.forEach((item) => {
          if (this.selectedRowKeys.includes(item.id)) {
            params.push({
              id: item.id,
              patient_sn: item.patient_sn,
              magic4: item.magic4,
            });
          }
        });
        const res = await blindEditing(this.RECORD_URL, { rows: params });
        if (res.code == 200) {
          this.$message.success("编盲成功!");
          this.getRecord();
          addLogInfo(this.SERVERBASE_URL, {
            name: this.userInfo.name,
            type: "操作",
            event: "编盲",
          });
        } else {
          this.$message.error("编盲失败!");
        }
        console.log("编盲 ", params);
      } catch (error) {
        console.log("blindEditing error", error);
      }
    },
    //导出数据到word
    async exportFiles2(val) {
      let params = {
        page: 1,
        limit: 500,
        level: this.userInfo.level == 8 ? 1 : this.userInfo.level,
        name: this.userInfo.name,
        blind: this.blindReview ? 1 : 0,
        sNoList: [val.sNo],
      };
      const res = await getEvaluationExamRecordsFilter(this.RECORD_URL, params);
      if (res.code == 200) {
        const row = res.data.rows;
        if (row.length > 0) {
          const res = dellDataByForms(row);
          console.log("导出结果:", res);
          res.forEach((item) => {
            exportToWord(item.param, item.name, item.type);
          });
        } else {
          console.log("导出数据到word：没有检查记录");
        }
      } else {
        console.log("导出获取数据失败");
      }
      addLogInfo(this.SERVERBASE_URL, {
        name: this.userInfo.name,
        type: "操作",
        event: "导出",
      });
    },
    //导出数据到pdf
    async exportFiles3(val) {
      let params = {
        page: 1,
        limit: 500,
        level: this.userInfo.level == 8 ? 1 : this.userInfo.level,
        name: this.userInfo.name,
        blind: this.blindReview ? 1 : 0,
        sNoList: [val.sNo],
      };
      const res = await getEvaluationExamRecordsFilter(this.RECORD_URL, params);
      if (res.code == 200) {
        const row = res.data.rows;
        if (row.length > 0) {
          const res = dellDataByForms(row);
          console.log("导出结果:", res);
          res.forEach((item) => {
            exportToWord2(item.param, item.name, item.type);
          });
        } else {
          console.log("导出数据到word：没有检查记录");
        }
      } else {
        console.log("导出获取数据失败");
      }
      addLogInfo(this.SERVERBASE_URL, {
        name: this.userInfo.name,
        type: "操作",
        event: "导出",
      });
    },
    //批量导出到zip
    async batchExportToExcel() {
      try {
        const vm = this;
        if (this.selectedRowKeys.length == 0) {
          this.$message.warning("请选择需要批量导出的记录！");
          return;
        }
        let exportRecordSno = [];
        let exportRecordSnoMap = {};
        let exportRecordData = [];
        let exportBuffer = [];
        const zip = new JSZip();
        this.tableData.forEach((item) => {
          if (this.selectedRowKeys.includes(item.id)) {
            exportRecordSno.push(item.sNo);
          }
        });
        const uniqueRecordSno = [...new Set(exportRecordSno)];
        if (uniqueRecordSno.length < 0) {
          return;
        }
        this.export_modal = true;
        let params = {
          page: 1,
          limit: 500,
          level: this.userInfo.level == 8 ? 1 : this.userInfo.level,
          name: this.userInfo.name,
          blind: this.blindReview ? 1 : 0,
          sNoList: uniqueRecordSno,
        };
        const res = await getEvaluationExamRecordsFilter(
          this.RECORD_URL,
          params
        );
        if (res.code == 200) {
          const rows = res.data.rows;
          if (rows.length > 0) {
            rows.forEach((item) => {
              if (exportRecordSnoMap[item.sNo]) {
                exportRecordSnoMap[item.sNo].push(item);
              } else {
                exportRecordSnoMap[item.sNo] = [];
                exportRecordSnoMap[item.sNo].push(item);
              }
            });
            console.log("exportRecordSnoMap", exportRecordSnoMap);
            for (let p in exportRecordSnoMap) {
              exportRecordData.push(dellDataByForms(exportRecordSnoMap[p]));
            }
            console.log("exportRecordData", exportRecordData);
            let exportBuffer1D = exportRecordData.flat();
            console.log("exportBuffer1D", exportBuffer1D);
            exportBuffer1D.forEach((item) => {
              exportBuffer.push(
                exportToWord(item.param, item.name, item.type, "blob")
              );
            });
            Promise.all(exportBuffer).then((res) => {
              console.log("exportBuffer all then res", res);
              for (const { fileName, file } of res) {
                zip.file(fileName, file);
              }
              zip.generateAsync({ type: "blob" }).then(function (con) {
                vm.export_modal = false;
                saveAs(con, "评价数据.zip");
              });
              addLogInfo(this.SERVERBASE_URL, {
                name: this.userInfo.name,
                type: "操作",
                event: "批量导出",
              });
            });
          } else {
            console.log("导出数据到word：没有检查记录");
          }
        } else {
          this.export_modal = false;
          console.log("导出获取数据失败");
        }
      } catch (error) {
        this.export_modal = false;
        console.log("relation error", error);
      }
    },
    //批量按日期导出
    async batchExportByDate() {
      const vm = this;
      if (this.selectedRowKeys.length == 0) {
        this.$message.warning("请选择需要批量导出的记录！");
        return;
      }
      const exportRecord = [];
      this.tableData.forEach((item) => {
        if (this.selectedRowKeys.includes(item.id)) {
          exportRecord.push(item);
        }
      });
      let key = true;
      exportRecord.forEach((item) => {
        key = item.forms ? item.forms.every((i) => i.evaluationResult) : false;
      });
      console.log("batchExportByDate key", key);
      if (!key) {
        this.$message.warning("导出记录中有未评价的！");
        return;
      }
    },
    // async exportFiles2(val) {
    //   try {
    //     if (val.pos == "腹部") {
    //       const params = dellDataByRecord(val);
    //       for (const p in params) {
    //         const params_item = params[p];
    //         const fileName = `${val.sNo}-${p}`;
    //         if (params_item) {
    //           exportToExcel(params_item, fileName, "xlsx");
    //         } else {
    //           console.log("导出失败", params_item);
    //         }
    //       }
    //     } else {
    //       const params = dellDataByRecord(val);
    //       const fileName = `${val.sNo}-${val.pos}`;
    //       if (params) {
    //         console.log("导出", params);
    //         exportToExcel(params, fileName, "xlsx");
    //       } else {
    //         console.log("导出失败", params);
    //       }
    //     }
    //     addLogInfo(this.SERVERBASE_URL, {
    //       name: this.userInfo.name,
    //       type: "操作",
    //       event: "导出",
    //     });
    //   } catch (error) {
    //     console.log("relation error", error);
    //   }
    // },
    //批量导出
    // async batchExportToExcel() {
    //   try {
    //     if (this.selectedRowKeys.length == 0) {
    //       this.$message.warning("请选择需要批量导出的记录！");
    //       return;
    //     }
    //     const vm = this;
    //     let exportRecord = [],
    //       exportBuffer = [];
    //     const zip = new JSZip();
    //     this.tableData.forEach((item) => {
    //       if (this.selectedRowKeys.includes(item.id)) {
    //         exportRecord.push(item);
    //       }
    //     });
    //     if (exportRecord.length > 0) {
    //       this.export_modal = true;
    //       exportRecord.forEach((item) => {
    //         if (item.pos == "腹部") {
    //           const params = dellDataByRecord(item);
    //           for (const p in params) {
    //             const params_item = params[p];
    //             const fileName = `${item.sNo}-${p}`;
    //             if (params_item) {
    //               exportBuffer.push({
    //                 file: exportToExcel(params_item, fileName, "zip"),
    //                 fileName,
    //               });
    //             }
    //           }
    //         } else {
    //           const params = dellDataByRecord(item);
    //           const fileName = `${item.sNo}-${item.pos}`;
    //           if (params) {
    //             console.log("导出", params);
    //             exportBuffer.push({
    //               file: exportToExcel(params, fileName, "zip"),
    //               fileName,
    //             });
    //           } else {
    //             console.log("导出失败", params);
    //           }
    //         }
    //       });
    //       for (const { fileName, file } of exportBuffer) {
    //         // console.log("fileName",fileName,"file",file)
    //         this.export_pro = Math.floor(
    //           100 / exportBuffer.length + this.export_pro
    //         );
    //         zip.file(fileName, file);
    //       }
    //       zip.generateAsync({ type: "blob" }).then(function (con) {
    //         console.log("评价数据:", con);
    //         saveAs(con, "评价数据.zip");
    //         if (vm.export_pro >= 95) {
    //           vm.export_modal = false;
    //           vm.$message.success("导出完成!");
    //           vm.export_pro = 0;
    //         }
    //       });
    //       addLogInfo(this.SERVERBASE_URL, {
    //         name: this.userInfo.name,
    //         type: "操作",
    //         event: "批量导出",
    //       });
    //     } else {
    //       this.export_modal = false;
    //       this.export_pro = 0;
    //       this.$message.warning("没有可以导出的记录!");
    //     }
    //     console.log("exportBuffer", exportBuffer);
    //   } catch (error) {
    //     this.export_modal = false;
    //     this.export_pro = 0;
    //     console.log("relation error", error);
    //   }
    // },
    async batchExportBlind() {
      try {
        let params = {
          page: 1,
          limit: this.total || 500,
          level: this.userInfo.level,
          name: this.userInfo.name,
          blind: this.blindReview ? 1 : 0,
        };
        getEvaluationExamRecords(this.RECORD_URL, params).then((res) => {
          if (res.code == 200) {
            const tableData = res.data.rows;
            let record = [];
            tableData.forEach((item) => {
              if (item.sNo && item.magic6) {
                record.push({ sNo: item.sNo, magic6: item.magic6 });
              }
              record = record.sort((a, b) => a.magic6 - b.magic6);
            });
            const map = {
              sNo: "受试者筛选号",
              magic6: "编盲号",
            };
            exportXlsxFile(record, map, "编盲记录", "report");
            console.log("batchExportBlind", record);
          }
        });
        addLogInfo(this.SERVERBASE_URL, {
          name: this.userInfo.name,
          type: "操作",
          event: "导出编盲记录",
        });
      } catch (e) {
        console.log("batchExportBlind err :", e);
      }
    },
  },
};
</script>

<style scoped lang="less">
@import "~@/assets/css/record.less";
</style>
